#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
import sys
import math

def extract_file_info(text, folder_path):
    # 获取所有可能的文件名及其在文本中的位置
    file_info = []
    for filename in os.listdir(folder_path):
        if filename.lower().endswith('.mp4'):
            name_without_ext = os.path.splitext(filename)[0]
            cleaned_name = clean_filename(name_without_ext)
            index = text.find(cleaned_name)
            if index != -1:
                file_info.append((index, cleaned_name))
    
    # 根据在文本中的位置排序
    return [name for _, name in sorted(file_info)]

def clean_filename(filename):
    # 移除文件名开头的数字和空格
    cleaned_name = re.sub(r'^\d+\s*-?\s*', '', filename)
    # 移除可能剩余的前导和尾随空格
    return cleaned_name.strip()

def rename_files(folder_path, file_info):
    renamed_count = 0
    skipped_count = 0

    # 确定编号格式
    file_count = len(file_info)
    number_of_digits = math.ceil(math.log10(file_count + 1))

    for index, cleaned_name in enumerate(file_info, start=1):
        # 查找匹配的原始文件名
        original_filename = next((f for f in os.listdir(folder_path) 
                                  if clean_filename(os.path.splitext(f)[0]) == cleaned_name 
                                  and f.lower().endswith('.mp4')), None)
        
        if original_filename:
            new_filename = f"{index:0{number_of_digits}d} {cleaned_name}.mp4"
            old_path = os.path.join(folder_path, original_filename)
            new_path = os.path.join(folder_path, new_filename)
            
            if old_path != new_path:
                os.rename(old_path, new_path)
                print(f"Renamed: {new_filename}")
                renamed_count += 1
        else:
            print(f"Skipped: {cleaned_name} (file not found in folder)")
            skipped_count += 1
    
    print(f"\nTotal files renamed: {renamed_count}")
    print(f"Total files skipped: {skipped_count}")

def read_text_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except IOError as e:
        print(f"Error reading file: {e}")
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python script_name.py <folder_path> <text_file_path>")
        sys.exit(1)
    
    folder_path = sys.argv[1]
    text_file_path = sys.argv[2]
    
    if not os.path.isdir(folder_path):
        print(f"Error: '{folder_path}' is not a valid directory.")
        sys.exit(1)
    
    if not os.path.isfile(text_file_path):
        print(f"Error: '{text_file_path}' is not a valid file.")
        sys.exit(1)
    
    text = read_text_file(text_file_path)
    file_info = extract_file_info(text, folder_path)
    rename_files(folder_path, file_info)
